# -*- coding: utf-8 -*-
import os.path
from ..globals import request


class _IgnoreException(object):
    def __enter__(self):
        pass

    def __exit__(self, type, value, tb):
        return True
ignore_exception = _IgnoreException()


def shell(namespace=None):
    banner = "accost debug shell"
    if namespace is None:
        namespace = {}
    try:
        import IPython
    except ImportError:
        from code import interact
        interact(banner, local=namespace)
        return
    else:
        sh = IPython.Shell.IPShellEmbed(banner=banner)
        sh(global_ns=globals(), local_ns=namespace)
        return


_missing = object()
class CachedProperty(object):
    def __init__(self, func, name=None, doc=None):
        self.__name__ = "cached_property." + (name or func.__name__)
        self.__module__ = func.__module__
        self.__doc__ = doc or func.__doc__
        self.func = func

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        value = request.__dict__.get(self.__name__, _missing)
        if value is _missing:
            value = self.func(obj)
            request.__dict__[self.__name__] = value
        return value


class AutoMTime(object):
    def __init__(self, root):
        self.root = root
        self.files = {}

    def __call__(self, path):
        if path in self.files:
            return self.files[path]
        realpath = os.path.join(self.root, path[1:])
        mtime = int(os.path.getmtime(realpath))
        ret = "%s?%s"%(path, mtime)
        self.files[path] = ret
        return ret

